<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        div{
            width: 100px;
            height: 100px;
            background-color: blueviolet;
            position: absolute;
            left: 0;
            top: 0;
        }
        div:hover{
            cursor: move;
        }
    </style>
    <script src="../js/documentMyReady.js"></script>
    <script>
        //1 dom： mousedown 的时候 监听 document: mousemove 和 mouseup 
        //2 mousemove 的时候 将鼠标位置 和 div 位置同步
        //3 mouseup 的时候 清空mouseup事件 和 mousemove事件，（注意mousedown一直都要被监听，所以不能清空）
        document.myReady(function(){
            //获取dom元素
            var dom = document.getElementsByTagName('div')[0];
            //获取dom的宽度和高度,减少重新获取的内存消耗
            var domWidth = dom.offsetWidth;
            var domHeight = dom.offsetHeight;
            //设定 mousedown, mouseup, mousemove 该做的事情
            let mousedownFun = function(){
                console.log('mousedown');
                document.addEventListener('mouseup',mouseupFun,false);
                document.addEventListener('mousemove',mousemoveFun,false); 
            }
            let mouseupFun = function(){
                console.log('mouseup');
                document.removeEventListener('mousemove',mousemoveFun,false);
                document.removeEventListener('mouseup',mouseupFun,false);
            }
            let mousemoveFun = function(e){
                console.log('mousemove');
                dom.style.left = e.pageX - domWidth/2 + 'px';
                dom.style.top = e.pageY - domHeight/2 + 'px';
            }
            dom.addEventListener('mousedown',mousedownFun,false);            
        })
    </script>
</head>
<body>
    <div></div>
</body>
</html>